import { supabase } from "@/supabase/supabaseClient";
import store from "../..";

let timer;
export default {
  state() {
    return {
      userId: null,
      token: null,
      error: null,
      didAutoLogout: false
    };
  },
  mutations: {
    setUser(state, payload) {
      state.userId = payload.userId;
      state.token = payload.token;
      state.didAutoLogout = false;
    },
    setAutoLogout(state) {
      state.didAutoLogout = true
    }
  },
  actions: {
    async login(context, payload) {
      const { data, error } = await supabase.auth.signInWithPassword({
        email: payload.email,
        password: payload.password,
      });
      console.log("login error", error);
      console.log("login data", data);

      if (error) {
        context.state.error = error.message;
        return;
      }

      const expiresIn = +data.session.expires_in * 1000;
      // const expiresIn = 5000;
      const expirationDate = new Date().getTime() + expiresIn;

      localStorage.setItem("userId", data.user.id);
      localStorage.setItem("token", data.session.access_token);
      localStorage.setItem("tokenExpiration", expirationDate);

      timer = setTimeout(function () {
        context.dispatch('autoLogout')
      }, expiresIn);

      context.state.error = null;
      context.commit("setUser", {
        userId: data.user.id,
        token: data.session.access_token,
      });
    },

    async signup(context, payload) {
      const { data, error } = await supabase.auth.signUp({
        email: payload.email,
        password: payload.password,
        options: {
          emailRedirectTo: "http://localhost:5173/",
        },
      });
      console.log("signup error", error);
      console.log("signup data", data);

      if (error) {
        context.state.error = error.message;
        return;
      }
      context.state.error = null;
      context.commit("setUser", {
        userId: data.user.id,
        token: null,
      });
    },
    tryLogin(context) {
      const token = localStorage.getItem("token");
      const userId = localStorage.getItem("userId");
      const tokeExpiration = localStorage.getItem("tokenExpiration");

      const expiresIn = +tokeExpiration - new Date().getTime();

      if (expiresIn < 0) {
        return;
      }

      timer = setTimeout(function () {
        context.dispatch('autoLogout')
      }, expiresIn);


      if (token && userId) {
        context.commit("setUser", {
          token: token,
          userId: userId,
        });
      }
    },
    async logout(context) {
      localStorage.removeItem("token");
      localStorage.removeItem("userId");
      localStorage.removeItem("tokenExpiration");

      clearTimeout(timer);

      context.commit("setUser", {
        token: null,
        userId: null,
      });
    },
    autoLogout(context) {
      context.dispatch('logout')
      context.commit('setAutoLogout')
    }
  },
  getters: {
    userId(state) {
      return state.userId;
    },
    error(state) {
      return state.error;
    },
    token(state) {
      return state.token;
    },
    isAuthenticated(state) {
      return !!state.token;
    },
    didAutoLogout(state) {
      return state.didAutoLogout
    }
  },
};
